#!/bin/bash

# Example of config see at end of this file
. ~/.config/repomirror/repomirror.conf

: ${LOCAL_REPO_DIR?'You must provide env var LOCAL_REPO_DIR - local root of repo (directly or in config ~/.config/repomirror/repomirror.conf)!'}
: ${REPOS?'You must provide env var REPOS - subdirs to sync (directly or in config ~/.config/repomirror/repomirror.conf)!'}
: ${LOGFILE?'You must provide env var LOGFILE (directly or in config ~/.config/repomirror/repomirror.conf)!'}

############################################################

# http://unix.stackexchange.com/questions/1496/why-doesnt-my-bash-script-recognize-aliases
shopt -s expand_aliases
source ~/.bashrc

#Renice himself
renice ${NICE-19} $$
sudo ionice -c${IONICE-3} -p$$

function repoUpdate(){
#$1 - In repodir.
#$2 - Out dir where placed repodata directory
#$3 - Logfile.

# --checksum sha for compatability with EPEL5
# xz compression type is not supported by COPR - http://copr-be.cloud.fedoraproject.org/results/hubbitus/test/fedora-20-x86_64/python-nbxmpp-0.4-1.fc20/root.log
createrepo_c --update --checksum sha -d -o "$1" "$2" | tee -a "$3"
}

{
	for distr in ${REPOS[*]} ; do
		pushd "$LOCAL_REPO_DIR/$distr"
		repoUpdate ./ ./ "$LOGFILE"

		if [ ! -z "$FTP_HOST" ]; then
			lftp -c 'open -e "mirror -caveR \
				--exclude=.htaccess \
				--exclude=header.htm \
				--exclude=_h5ai.headers.html \
				--exclude=_h5ai \
				--delete-first \
				'"$LOCAL_REPO_DIR/$distr"' '"$FTP_DIR/$distr"'" \
					'"$FTP_HOST"
		else
			if [ ! -z "$RSYNC_URL" ]; then
				rsync_s --delete "$LOCAL_REPO_DIR/$distr/" "$RSYNC_URL/$distr/"
			fi
		fi
		echo "$distr DONE"
		popd
	done

echo 'Repo updated'
} 2>&1 | tee "$LOGFILE"


# Sample config (must be placed in ~/.config/repomirror/repomirror.conf):
##LOCAL_REPO_DIR=/local/path/RPM_REPO/
## All
##REPOS=( $( ls "$LOCAL_REPO_DIR" ) )
## Chosen
#REPOS=( Fedora20 Fedora21 Fedora22 EL6 epel7 )
#
#LOGFILE=$HOME/repomirror.log
#
## You may define pair FTP_HOST/FTP_DIR (in that cale lftp mirror will be used) or RSYNC_URL, not both!
##FTP_HOST=ftp.example.org
##FTP_DIR=/var/www/rpms
#
## In last part REPOS will be added
#RSYNC_URL=rsync.example.org:/var/www/rpms/
